package com.example.common.view.view

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
import androidx.databinding.ViewDataBinding
import com.example.base.app.view.BaseFragment
import com.example.common.view.event.CustomEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * MVVM架构模式下的BaseFragment
 */
open class BaseMvvmFragment<VDB:ViewDataBinding>: BaseFragment<VDB>() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //获取数据
        loadData()
        //订阅数据
        observeDataChange()
        //EventBus事件总线
        EventBus.getDefault().register(this)
    }
    //接收事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReceiveEvent(event: CustomEvent?){
        //校验是否是当前页面接收事件
        if(event != null && event.target == this.javaClass.simpleName){
            handEvent(event)
        }
    }
    //反注册
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    /********** 使用AndroidX提供合约模式实现页面之间传值 *****Start*****/
    //获取启动器
    private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        run {
            //成功返回（下一页使用setResult（Intent)）
            if(result.resultCode == RESULT_OK){
                result.data?.let {handActivityResult(it)}
            }
        }
    }

    //启动下一个Activity并接收返回结果
    protected open fun startNextActivityForResult(intent: Intent, requestCode:Int){
        intent?.run {
            //相当于startActivity(this)
            resultLauncher.launch(intent)
        }
    }

    //子类获取页面返回的Intent对象，并从中获取
    protected open fun handActivityResult(data: Intent){}
    /************* 使用AndroidX提供合约模式实现页面之间传值 *****End*****/

    /********** 系统提供API实现页面之间传值 **********/
    protected open fun startNextActivity(intent: Intent){
        intent?.run {
            startActivity(this)
        }
    }

    protected open fun handEvent(event: CustomEvent){}

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        recevieNextForResult(requestCode,resultCode,data)
    }

    protected open fun recevieNextForResult(requestCode: Int, resultCode: Int, data: Intent?){}
    //可以根据业务逻辑需要重写方法
    protected open fun observeDataChange(){}
    //可以根据业务逻辑需要重写方法
    protected open fun loadData(){}
}